package com.joy.openggl.graphics;

import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;

import com.joy.openggl.graphics.proto.RectangleF;
import com.joy.openggl.util.BufferUtil;

public class Image {

	private Texture2D tex;
	private int mWidth;
	private int mHeihgt;
	private int mPowWidth;
	private int mPowHeight;
	
	public static Image create(Bitmap bmp) {
		Image img = new Image();
		img.init(bmp);
		
		return img;
	}
	
	private void init(Bitmap bmp) {
		tex = Texture2D.create(bmp);
		mWidth = tex.size.width;
		mHeihgt = tex.size.height;
		mPowWidth = tex.rect.width;
		mPowHeight = tex.rect.height;
	}
	
	/** Our vertex buffer. */
	 private FloatBuffer mVerticesBuffer = null;
	 /** Our texcoord buffer. */
	 private FloatBuffer mTexcoordsBuffer = null;
	 /** Our index buffer. */
	 private ShortBuffer mIndicesBuffer = null;
	 /** The number of indices. */
	 private int mNumOfIndices = -1;

	 public void draw(GL10 gl, float x, float y, float clipx, float clipy, float clipw, float cliph) {
		 gl.glEnable(GL10.GL_TEXTURE_2D);
		 gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		 gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		 
		 gl.glBindTexture(GL10.GL_TEXTURE_2D, tex.texId);
		 
		 gl.glTranslatef(x, y, 0);
		 // 获取将要绘制的区域和Image本身的剪切区域的交集
		 RectangleF rect = RectangleF.intersection(0, 0, mWidth, mHeihgt, 
				clipx, clipy, clipw, cliph);
		 mVerticesBuffer = BufferUtil.getVerticesBuffer(0, 0, rect.width, rect.height);
		 mTexcoordsBuffer = BufferUtil.getTexcoordsBuffer(rect.x, rect.y, rect.width, rect.height, 
				mPowWidth, mPowHeight);
		 //设置正方体 各顶点
		 gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mVerticesBuffer);
	     gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexcoordsBuffer);
	     gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
	    
	    
		 gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		 gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		 gl.glDisable(GL10.GL_TEXTURE_2D);
	}
}
